//
//  AddressManager.swift
//  JiaoZiTaxi
//
//  Created by hc-101 on 2024/7/6.
//

import SwiftUI
import MapKit

struct CoomonAddressManagerView: View {
    
    var vm = ViewModel.shared
    
    @Environment(\.dismiss) var dismiss
       
    @State var region: MKCoordinateRegion
    
    @State var selectCoordinate: CLLocationCoordinate2D
    
    @State var selectType: String
    
    @ObservedObject var carOrder = CarOrder.shared
    @StateObject private var addressManager = MyAddressNetManager()
    
    @State private var keyword: String = ""     // 搜索地址名称
    @State var addAddressAction: Bool = false    // 是否添加位置
    @State var isPublic: Bool = false           // 是公开地址
    @State private var addressName: String = ""
    @State var aId: String = ""
    @State var showAlert = false        // 是否展示弹框
    @State var showSheet = false
    
    var segmentTypes: [SegmentModel] = [SegmentModel(title: "公共定位".localized(),request: "public"),
                                        SegmentModel(title: "私有定位".localized(),request: "private")]
    @State private var selected : SegmentModel = SegmentModel(title: "公共定位".localized(),request: "public")
    
 
    
    var action : (AddressModel)->Void
    
    
    
    var body: some View {
        GeometryReader(content: { geometry in
            
            NavigationView{
                VStack {
                    // MARK: 右上角的关闭页面按钮
                    HStack {
                        Button(action: {
                            dismiss()
                        }, label: {
                            HStack {
                                Image(systemName: "chevron.backward")
                                    .foregroundColor(.black)
                            }
                        })
                        Spacer()
                    }.padding(.horizontal, 20)
                    
                    // MARK: 中间三个tab按钮
                    createHoriSegment()
                        .padding(.horizontal,30)
                        .padding(.vertical,15)
                    // MARK: 下边的三个分页
                    ZStack {
                        // MARK: 2.私有定位位置页面
                        if self.selected.request == "private" {
                            ZStack {
                                VStack (spacing:0) {
                                    // 列表
                                    List{
                                        
                                        if addressManager.addressLocalList.count > 0 {
                                            
                                            HStack{
                                                Text("历史记录").font(.system(size: 18,weight: .bold)).foregroundColor(.black)
                                                Spacer()
                                                Button {
                                                    addressManager.clearLocalAddressList()
                                                } label: {
                                                    Text("清空").font(.system(size: 12)).foregroundColor(.gray)
                                                }.frame(width:60, height: 30)
                                            }
                                            .frame(maxWidth: .infinity, alignment: .leading).listRowSeparator(.hidden)
                                            
                                            ForEach(addressManager.addressLocalList, id: \.self) { address in
                                                Button {
                                                    self.action(address)
                                                    dismiss()
                                                } label: {
                                                    createPublicCell(address: address)
                                                    
                                                }
                                            }
                                           
                                            
                                        }
                                        if addressManager.addressPrivateList.count > 0 && addressManager.addressLocalList.count > 0 {
                                            
                                            Rectangle()
                                                .fill(Color.gray.opacity(0.1))
                                                .frame(height: 20).listRowInsets(EdgeInsets()).listRowSeparator(.hidden)
                                        }
                                        
                                        
                                        Section{
                                            
                                            ForEach(addressManager.addressPrivateList, id: \.self) { address in
                                                Button {
                                                    // 保存地址
                                                    if let addressModel = address as? AddressModel {
                                                        addressManager.setLocalAddress(address: address)
                                                    }
                                                    self.action(address)
                                                    dismiss()
                                                    
                                                } label: {
                                                    createPrivateCell(address: address)
                                                }
                                            }
                                        } header:{
                                            
                                        }
                                    }.listStyle(PlainListStyle())
                                        .padding(0)
                                        .background(.clear)
                                    Button(action: {
                                        self.addAddressAction = true
                                    }, label: {
                                        HStack {
                                            Image(systemName: "plus")
                                                .foregroundColor(.white)
                                            Text("添加位置")
                                        }
                                        .frame(width: 320, height: 48)
                                        .background(Color.themeColor())
                                        .foregroundColor(.white)
                                        .cornerRadius(6)
                                    })
                                }
                                .padding()
                                .frame(width: geometry.size.width)
                                .background(Color.backgroundColor())
                                // FIX: 无数据占位图
                                if addressManager.addressPrivateList.count <= 0  && addressManager.addressLocalList.count <= 0{
                                    VStack {
                                        Spacer()
                                        Image("no_data_holder")
                                            .resizable()
                                            .frame(width: 180, height: 165)
                                        Text("没有位置")
                                            .font(.system(size: 14))
                                            .foregroundColor(Color(hex: "#999999"))
                                        Spacer()
                                        Spacer()
                                    }
                                    .padding(.horizontal, 100)
                                }
                            }.onAppear {
                                addressManager.loadAddressList(index: self.selected.request, keyword: keyword)
                                addressManager.loadLocalAddressList()
                            }
                            
                            // add address blank
                            if self.addAddressAction {
                                Color.black.opacity(0.5)
                                createAddAddressView()
                            }
                        }
                        
                        // MARK: 3.选择位置页面
                        if self.selected.request == "public" {
                            VStack {
                                HStack {
                                    Image(systemName: "magnifyingglass")
                                        .foregroundColor(Color(hex: "#999999"))
                                    TextField("您要去哪儿", text: $keyword).padding()
                                    Button(action: {
                                        addressManager.loadAddressList(index: self.selected.request, keyword: keyword)
                                        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                                    }, label: {
                                        Text("搜索")
                                            .font(.system(size: 14))
                                            .foregroundColor(.white)
                                    })
                                    .frame(width: 60, height: 30)
                                    .background(Color.themeColor())
                                    .cornerRadius(4)
                                    
                                }
                                .padding(.horizontal , 12)
                                .background(.white)
                                .cornerRadius(6)
                                
                                
                                
                                
                                // 列表
                                List {
                                    if addressManager.addressLocalList.count > 0 {
                                        
                                        HStack{
                                            Text("历史记录").font(.system(size: 18,weight: .bold)).foregroundColor(.black)
                                            Spacer()
                                            Button {
                                                addressManager.clearLocalAddressList()
                                            } label: {
                                                Text("清空").font(.system(size: 12)).foregroundColor(.gray)
                                            }.frame(width:60, height: 30)
                                        }
                                        .frame(maxWidth: .infinity, alignment: .leading).listRowSeparator(.hidden).background(.white)
                                        
                                        ForEach(addressManager.addressLocalList, id: \.self) { address in
                                            Button {
                                                
                                                self.action(address)
                                                dismiss()
                                            } label: {
                                                createPublicCell(address: address).background(.white)
                                                
                                            }.background(.white)
                                            //                                        if address == $addressManager.addressLocalList.last {
                                            //                                            .listRowSeparator(.hidden)
                                            //                                        }
                                        }
                                        
                                        
                                    }
                                    
                                    if addressManager.addressPublicList.count > 0 && addressManager.addressLocalList.count > 0 {
                                        
                                        Rectangle()
                                            .fill(Color.gray.opacity(0.1))
                                            .frame(height: 20).listRowInsets(EdgeInsets()).listRowSeparator(.hidden)
                                    }
                                    
                                    
                                    ForEach(addressManager.addressPublicList, id: \.self) { address in
                                        Button {
                                            self.action(address)
                                            dismiss()
                                            
                                        } label: {
                                            createPublicCell(address: address)
                                        }
                                    }
                                }
                                .listStyle(PlainListStyle())
                                .padding(.vertical,15)
                                .background(.clear)
                                
                            }
                            .padding(10)
                            .frame(width: geometry.size.width)
                            .background(Color.backgroundColor())
                            .onAppear {
                                addressManager.loadLocalAddressList()
                                addressManager.loadAddressList(index: self.selected.request, keyword: keyword)
                            }
                        }
                    }
                }
            }  .navigationBarHidden(true)
        })
        
    }
    
    func addAddress(text: String) {
        if text.isEmpty {
            return
        }
        saveAddressAction(aId: self.aId, name: self.addressName, lat: "\(self.selectCoordinate.latitude)", lon: "\(self.selectCoordinate.longitude)", type: self.isPublic ? "public" : "private") { result in
            self.addAddressAction = false
            if !self.isPublic {
                addressManager.loadAddressList(index: self.selected.request, keyword: "")
            }
        }
        
    }
    
    func deletAddress() {
        let openId = ViewModel.shared.passenger.openId
        Api.deleteAddress(aId: self.aId, openId: openId) { r in
            addressManager.loadAddressList(index: "private", keyword: "")
        }
    }
    
}

private extension CoomonAddressManagerView {
    //
    func createHoriSegment()->some View{
        HStack {
            RadioButton(item: self.segmentTypes[0], selectedOption: $selected) {
                self.selected = self.segmentTypes[0]
            }
            Spacer()
            Image("more-square")
            Spacer()
            
            RadioButton(item: self.segmentTypes[1], selectedOption: $selected) {
                self.selected = self.segmentTypes[1]
            }
            Spacer()
            Image("more-square")
            Spacer()
            NavigationLink (destination:  SelectMapPointManager(action: { address in
                self.action(address)
                dismiss()
            })){
                HStack(spacing: 5){
                    HStack {
                        Image("地图选点_设置").resizable().frame(width:16, height:16)
                        Text("地图选点").font(.system(size: 13)).foregroundColor(.black)
                    }
                    .padding(.vertical, 8)
                        
                    }
                }
        }
    }
    
    func createAddAddressView()->some View{
        VStack {
            Spacer()
            VStack {
                VStack (spacing: 10) {
                    VStack {
                        TextField("您要去哪儿", text: $addressName).padding()
                    }
                    .frame(height: 46)
                    .padding(.horizontal, 10)
                    .background(Color(hex: "#EBEDF5"))
                    
                    HStack {
                        Text("\(self.selectCoordinate.longitude)")
                        Spacer()
                    }
                    .frame(height: 46)
                    .padding(.horizontal, 20)
                    .background(Color(hex: "#EBEDF5"))
                    
                    HStack {
                        Text("\(self.selectCoordinate.latitude)")
                        Spacer()
                    }
                    .frame(height: 46)
                    .padding(.horizontal, 20)
                    .background(Color(hex: "#EBEDF5"))
                    
                    HStack {
                        Button {
                            self.isPublic = false
                        } label: {
                            HStack {
                                Image(systemName: self.isPublic ? "circle" : "checkmark.circle.fill")
                                    .foregroundColor(self.isPublic ? Color.black  : Color.themeColor())
                                Text("私有")
                                    .font(.system(size: 16))
                                    .foregroundColor(.black)
                            }
                            .frame(width: 80, height:30)
                        }

                        Button {
                            self.isPublic = true
                        } label: {
                            HStack {
                                Image(systemName: self.isPublic ? "checkmark.circle.fill" : "circle")
                                    .foregroundColor(self.isPublic ? Color.themeColor() : Color.black)
                                Text("公开")
                                    .font(.system(size: 16))
                                    .foregroundColor(.black)
                            }
                            .frame(width: 80, height:30)
                        }
                        
                        Spacer()
                        
                        Button { // 更新经纬度方法
                            
                        } label: {
                            HStack {
                                Image(systemName: "arrow.clockwise")
                                Text("更新经纬度")
                                    .font(.system(size: 16))
                            }
                            .frame(width: 120, height:30)
                            .foregroundColor(Color.themeColor())
                        }
                    }
                    .padding(.vertical, 10)
                    
                    HStack {
                        // 取消按钮
                        Button {
                            self.addAddressAction = false
                        } label: {
                            HStack {
                                Text("取消")
                                    .font(.system(size: 17))
                            }
                            .frame(width: 150, height:44)
                            .foregroundColor(.black)
                            .background(Color(hex: "#F7F7F7"))
                            .cornerRadius(6)
                        }
                        
                        Spacer()
                        // 保存按钮
                        Button {
                            self.showAlert = addressName.isEmpty
                            self.addAddress(text: addressName)
                        } label: {
                            HStack {
                                Text("保存")
                                    .font(.system(size: 17))
                            }
                            .frame(width: 150, height:44)
                            .foregroundColor(.white)
                            .background(Color.themeColor())
                            .cornerRadius(6)
                        }.alert(isPresented: $showAlert, content: {
                            Alert(title: Text("请填写地址名称"))
                        })
                    }
                    .padding(.vertical, 20)
                    
                }.padding(20)
            }
            .background(Color(.white))
            .cornerRadius(8)
        }
    }
    
    //公共cell
    func createPublicCell(address : AddressModel) -> some View{
        HStack{
            Image("地图选点_设置")
            Text(getRecordName(address: address)).font(.system(size: 14))
        }.frame(maxWidth: .infinity, alignment: .leading)
            .padding(.vertical,10)
    }
  
    func getRecordName(address: AddressModel)->String{
        var name = address.name ?? ""
        if let addr = address.address {
            name = name + "/" + addr
        }
        return name
    }
    
    
    //私有cell
    func createPrivateCell(address : AddressModel) -> some View{
        HStack{
             Image("地图选点_设置")
            VStack(alignment:.leading){
                HStack{
                    Text(getRecordName(address: address)).font(.system(size: 14)).frame(maxWidth:.infinity,alignment: .leading)
                    Button {
                        print("地图_编辑 address:\(address.name ?? "")")
                        self.aId = address.id!
                        self.addressName = address.name!
                        self.addAddressAction = true
                    } label: {
                        Image("地图_编辑")
                    }
                    Spacer.width(20)
                    Button {
                        print("地图_删除 address:\(address.name  ?? "")")
                        self.aId = "\(address.id!)"
                        deletAddress()
                    } label: {
                        Image("地图_删除")
                    }
                    
                }
                Text("\(address.longitude!),\(address.latitude!)")
            }
        }.frame(maxWidth: .infinity, alignment: .leading).padding(.vertical,10)
    }
    
}
